//
//  OMCouponSelectionViewController.m
//  OMENGO
//
//  Created by 梁尚嘉 on 2016/12/29.
//  Copyright © 2016年 Kamfat. All rights reserved.
//

#import "OMCouponSelectionViewController.h"
#import "OMCouponSelectTableCell.h"
@interface OMCouponSelectionViewController ()

@end

@implementation OMCouponSelectionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.tableView.tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SM_SCREEN_WIDTH, SM_SIZE(30))];
    self.tableView.rowHeight = [OMCouponSelectTableCell cellHeight];
    self.tableView.sectionHeaderHeight = SM_SIZE(20);
    self.tableView.sectionFooterHeight = DBL_EPSILON;
    self.emptyDataMessage = @"暂无优惠券呢！";
    self.emptyImage = [UIImage imageNamed:@"ic_coupons_empty"];

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"不使用" style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonItemClick:)];

    //data request
    if (!self.coupons.count) {
        [self getValidCoupons];
    }
}

- (void)reloadDataFromNetWork
{
    [self getValidCoupons];
}

- (void)getValidCoupons
{
    [self startAnimating:YES];
    [KTHttpUtils GET_NOCACHE:@"member/couponCode/couponCode.jhtml" parameters:nil progress:nil completion:^(id responseObject, BOOL isSuccess, NSString *message) {
        if (isSuccess) {
            self.coupons = [OMCheapModel mj_objectArrayWithKeyValuesArray:responseObject[OMDataKey]];
            [self.tableView reloadData];
            [self startAnimating:NO];
        }else {
            
            [self showNetWorkError];
        }
    }];
}

- (void)rightBarButtonItemClick:(id)sender
{
    [self callbackWithObject:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.coupons.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    OMCouponSelectTableCell *cell = [OMCouponSelectTableCell tableViewCellWithTableView:tableView];
    [cell configureCellWithObj:self.coupons[indexPath.section]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self callbackWithObject:self.coupons[indexPath.section]];
}

- (void)callbackWithObject:(id)obj
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(ctrl:didSelectObject:)]) {
        [self.delegate ctrl:self didSelectObject:obj];
    }
    NaviPopAnimated(YES);
}


@end
